// pages/demand-publish/demand-publish.js
const app = getApp()

Page({
  data: {
    serviceTypes: [
      { id: 1, label: '医院陪护', value: 'care' },
      { id: 2, label: '跑腿买药', value: 'errand' },
      { id: 3, label: '上门护理', value: 'nursing' },
      { id: 4, label: '其他服务',value:'other'}
    ],
	images: [],
    currentServiceType: null,
    form: {
	  type:'',
      name: '',
      desc: '',
      price: '',
      phone: '',
	  nickname:'',
      image: []
    },
    formValid: false
  },

  onLoad() {
    this.checkAuth()
  },

  // 检查认证状态
  async checkAuth() {
	const isAuthorized = wx.getStorageSync('isAuthorized')
    if (!isAuthorized) {
      const res = await wx.showModal({
        title: '需要认证',
        content: '发布需求需要先完成实名认证',
        confirmText: '去认证'
      })
      if (res.confirm) {
        wx.navigateTo({ url: '/vp_pz/pages/staff/reg' })
      } else {
        wx.navigateBack()
      }
    }
  },

  // 表单输入处理
  changeServiceType(e) {
    this.setData({
      currentServiceType: this.data.serviceTypes[e.detail.value],
	  'form.type': this.data.serviceTypes[e.detail.value]
    }, this.validateForm)
  },

  onTitleChange(e) {
    this.setData({ 'form.name': e.detail.value }, this.validateForm)
  },

  onDescChange(e) {
    this.setData({ 'form.desc': e.detail.value }, this.validateForm)
  },

  onPriceChange(e) {
    this.setData({ 'form.price': e.detail.value }, this.validateForm)
  },

  onPhoneChange(e) {
    this.setData({ 'form.phone': e.detail.value }, this.validateForm)
  },
onNameChange(e) {
    this.setData({ 'form.nickname': e.detail.value }, this.validateForm)
  },
  // 图片操作
  async chooseImage() {
    // try {
		var self = this;
		let images_url = [];
		let tem_image = [];
		var url = app.util.url('Common/upload');
      const res = await wx.chooseImage({
        count: 3 - this.data.form.image.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
		success:function(res){
			wx.uploadFile({
			        url: url,
			        filePath: res.tempFilePaths[0],
			        name: 'file',
			        formData: {
			                'path': res.tempFilePaths[0]
			        },
			        success: function (ret) {
						console.log(ret)
			                let data = JSON.parse(ret.data);
			                console.log(data);
			
			                if (data.code!=1){
			                        wx.showModal({
			                                title: '图片上传失败',
			                                content: data.message,
			                                showCancel:false,
			                                success(res) {
			                                       
			                                }
			                        });
			                }else{
			       //                   images_url.push(data.data.path)
									 // tem_image.push(res.tempFilePaths[0])
									 self.setData({
									 		  'images':data.data.path,
									   'form.image': [...self.data.form.image, ...res.tempFilePaths]
									 })
			                }
			        }
			});
		}
      })
    // } catch (error) {
    //   console.log('取消选择')
    // }
	
  },

  deleteImage(e) {
    const index = e.currentTarget.dataset.index
    const images = this.data.form.image.filter((_, i) => i !== index)
    this.setData({ 'form.image': images })
  },

  previewImage(e) {
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls: this.data.form.image
    })
  },

  // 表单验证
  validateForm() {
    const { currentServiceType, form } = this.data
    const valid = currentServiceType &&
                 form.name.trim().length >= 5 &&
                 form.desc.trim().length >= 20 &&
                 form.price > 0 &&
                 /^1[3-9]\d{9}$/.test(form.phone)

    this.setData({ formValid: valid })
  },

  // 提交表单
  async handleSubmit() {
    if (!this.data.formValid) return
	let self = this
    // try {
      wx.showLoading({ title: '发布中...' })
      
      // 模拟提交
       // 序列化提交数据对象      
				this.data.form.image = this.data.images
				this.data.form.type = this.data.form.type.value;
              app.util.request({
                      url: 'Xuqiu/publish',
                      data: this.data.form,
                      success(res) {
                          wx.showModal({
                              title:'发布成功',
                              content: res.data.msg,
                              confirmText: '确定',
                              showCancel: false,
                              success:function(){
								  wx.navigateTo({
								    url: `/vp_pz/pages/xqfb/index`
								  })
                                 
                              }
                          });
                      }
              })

      wx.hideLoading()
    // } catch (error) {
    //   wx.hideLoading()
    //   wx.showToast({ title: '发布失败', icon: 'none' })
    // }
  },
})